#include <vector>
#include<array>
#include<string>

class Solution {
public:
    int longestSubstring(std::string s, int k) {
        std::array<int,26> arr;

        int n = s.size();
        int ans =0;
        for (int i=1; i<=26; i++)
        {
            arr.fill(0);
            for (int r=0,l=0,co=0,sa=0;r<n;r++)
            {
                arr[s[r]-'a']++;
                if (arr[s[r]-'a']==1)
                {
                    co++;
                }
                if (arr[s[r]-'a']==k)
                {
                    sa++;
                }
                while (co>i)
                {
                    arr[s[l]-'a']--;
                    if (arr[s[l]-'a']==0)
                    {
                        co--;
                    }
                    if (arr[s[l]-'a']==k-1)
                    {
                        sa--;
                    }
                    l++;
                }
                if (sa==i)
                {
                    ans=std::max(ans,r-l+1);
                }
            }
        }
        return ans;
    }
};
